﻿namespace Sample.Server;

class AppServer
{
    internal static void Initialize(WebApplicationBuilder builder)
    {
        KCConfig.WebRoot = builder.Environment.WebRootPath;
        KCConfig.ContentRoot = builder.Environment.ContentRootPath;

        var configuration = builder.Configuration;
        var dbFile = configuration.GetSection("DBFile").Get<string>();
        var uploadPath = configuration.GetSection("UploadPath").Get<string>();
        Initialize(dbFile, uploadPath);
    }

    internal static void Initialize(string? dbFile, string? uploadPath)
    {
        var rootPath = KCConfig.ContentRoot;
        if (!string.IsNullOrWhiteSpace(dbFile))
            dbFile = Path.GetFullPath(Path.Combine(rootPath, dbFile));
        else
            dbFile = InitDatabase();
        if (!string.IsNullOrWhiteSpace(uploadPath))
            uploadPath = Path.GetFullPath(Path.Combine(rootPath, uploadPath));

        Config.IsPlatform = true;
        AppConfig.Initialize();
        AppCore.Initialize();

        Database.RegisterProviders(new Dictionary<string, Type>
        {
            ["SQLite"] = typeof(Microsoft.Data.Sqlite.SqliteFactory)
        });
        var connInfo = new Known.Core.ConnectionInfo
        {
            Name = "Default",
            ProviderName = "SQLite",
            ConnectionString = $"Data Source={dbFile};"
        };
        KCConfig.App = new AppInfo
        {
            Connections = new List<Known.Core.ConnectionInfo> { connInfo },
            UploadPath = uploadPath
        };
    }

    private static string InitDatabase()
    {
        var fileName = "Sample.db";
        var path = Path.Combine(KCConfig.ContentRoot, "bin", fileName);
        if (!File.Exists(path))
        {
            Utils.EnsureFile(path);
            var assembly = typeof(AppServer).Assembly;
            var names = assembly.GetManifestResourceNames();
            var name = names.FirstOrDefault(n => n.Contains(fileName));
            using (var stream = assembly.GetManifestResourceStream(name))
            using (var fs = File.Create(path))
            {
                stream.CopyTo(fs);
            }
        }
        return path;
    }
}